/// <summary>
/// Copyright 2010 Ivo Limmen (ivo@limmen.org)
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
/// 
/// http://www.apache.org/licenses/LICENSE-2.0
/// 
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// </summary>

using System;
using System.Collections.Generic;
using Services.Configuration.Model.Meta;
using Services.Configuration.Api;

namespace Services.Configuration.Model
{
	public class Configuration : IResolver
	{
		private List<Section> sections = new List<Section>();
		
		private Documentation documentation = null;
		
		public Configuration ()
		{
		}
		
		public void SetDocumentation(Documentation documentation) 
		{
			this.documentation = documentation;
		}
		
		public Documentation GetDocumentation() 
		{
			return this.documentation;
		}
		
		public void AddSection(Section section) 
		{
			this.sections.Add(section);
		}
		
		public Section GetSectionByName(string name, string host) 
		{
			foreach (Section section in this.sections) 
			{
				if (section.GetName().Equals(name, StringComparison.InvariantCultureIgnoreCase)) 
				{
					if (!string.IsNullOrEmpty(host)) 
					{
						if (section.GetHost() != null && section.GetHost().Equals(host, StringComparison.InvariantCultureIgnoreCase)) 
						{
							return section;
						}
					}
					else {
					
						return section;
					}
				}
			}
			
			if (host != null) 
			{
				return GetSectionByName(name, null);
			}
			
			return null;
		}
				
		public bool IsEmpty()
		{
			return this.sections.Count == 0;
		}
		
		#region IResolver implementation
		
		public string GetSetting(string hostname, string sectionName, string keyName)
		{
			Section section = GetSectionByName(sectionName, hostname);
			
			if (section != null) 
			{
				Key key = section.GetKeyByName(keyName);
				
				if (key != null) 
				{
					return key.GetValue();
				}
				else {
					
					section = GetSectionByName(sectionName, null);
					
					key = section.GetKeyByName(keyName);
					
					if (key != null) 
					{
						return key.GetValue();
					}
				}
			}
			
			return null;
		}
		
		#endregion
	}
}
